import * as vscode from 'vscode';
import * as path from 'path';
import { MetaManager } from './MetaManager';

export class BookManager {
    public async isBook(): Promise<boolean> {
        const folders = vscode.workspace.workspaceFolders;
        if (!folders || folders.length === 0) { return false; }

        const root = folders[0].uri.fsPath;
        const marker = path.join(root, '.greatwriter');
        try {
            const stat = await vscode.workspace.fs.stat(vscode.Uri.file(marker));
            return (stat.type === vscode.FileType.Directory);
        } catch {
            return false;
        }
    }

    public newProject(): vscode.Disposable {
        return vscode.commands.registerCommand('greatwriter.newBook', async () => {
            const parentUri = await this.getParenUri();
            if (!parentUri) { return; }
            const bookName = await this.getBookName();
            if (!bookName) { return; }
            const author = await this.getAuthor();

            this.create(parentUri, bookName, author);
        });
    }

    private async getParenUri(): Promise<vscode.Uri | undefined> {
        const folders = await vscode.window.showOpenDialog({
            canSelectFiles: false,
            canSelectFolders: true,
            canSelectMany: false,
            openLabel: 'Select folder'
        });
        if (!folders || folders.length === 0) { return undefined; }
        return folders[0];
    }

    private async getBookName(): Promise<string | undefined> {
        return await vscode.window.showInputBox({
            prompt: 'Enter a name for your new book(Press "Enter" to confirm or "Escape" to cancel)',
            value: 'NewBook',
            title: 'New book name',
            validateInput: text => text.trim() ? undefined : 'Name cannot be empty'
        });
    }

    private async getAuthor(): Promise<string | undefined> {
        return await vscode.window.showInputBox({
            prompt: 'Enter author name(Press "Enter" to confirm or "Escape" to cancel)',
            placeHolder: 'author',
            title: 'Author Name'
        });
    }

    private async create(base: vscode.Uri, bookName: string, author: string | undefined) {
        const bookUri = vscode.Uri.joinPath(base, bookName);
        const dotUri = vscode.Uri.joinPath(bookUri, '.greatwriter');
        await vscode.workspace.fs.createDirectory(bookUri);
        
        await this.copyTemplate(dotUri);
        const metaData = new Map<string, any>([
            ['title', bookName],
            ['author', author],
        ]);
        await MetaManager.set(dotUri, metaData);
        await vscode.workspace.fs.writeFile(
            vscode.Uri.joinPath(bookUri, 'chapter-01.md'),
            new TextEncoder().encode('# 第一章')
        );

        await vscode.commands.executeCommand('vscode.openFolder', bookUri);
    }

    private async copyTemplate(destUri: vscode.Uri) {
        const extension = vscode.extensions.getExtension('leqijishu.greatwriter')!;
        const templateUri = vscode.Uri.joinPath(
            vscode.Uri.file(extension.extensionPath),
            'assets',
            '.greatwriter'
        );
        await vscode.workspace.fs.copy(templateUri, destUri);
    }
}
